#version 410

in vec2 texCoord;
in vec3 normal;
in vec3 tangent;
in vec4 worldPos;
flat in uint referenceIndex;

uniform sampler2D diffuseMap;
uniform sampler2D opacityMap;
uniform sampler2D normalMap;
uniform uint objectIndex;

// Shader should set to default value of -1
// if not picking will not work correctly
uniform int singleRefIndex;

layout (location = 0) out vec4 worldPosOut;
layout (location = 1) out vec4 colorOut;
layout (location = 2) out vec4 normalOut;
layout (location = 3) out uvec3 pickingOut;

vec3 calculateNormalMap()
{
    vec3 norm = normalize(normal);
    vec3 tang = normalize(tangent);
    tang = normalize(tang - dot(tang, norm) * norm);
    vec3 biTangent = cross(tang, norm);
    vec3 bmNormal = texture(normalMap, texCoord).xyz;
    bmNormal = 2.0 * bmNormal - vec3(1.0, 1.0, 1.0);
    vec3 nNormal;
    mat3 transBumpMap = mat3(tang, biTangent, norm);
    nNormal = transBumpMap * bmNormal;
    nNormal = normalize(nNormal);
    return nNormal;
}

void main()
{
	vec3 difCol = texture(diffuseMap, texCoord).rgb;
	float alpha = texture(opacityMap, texCoord).a;
	if (alpha != 1.0)
		discard;

    worldPosOut = worldPos;
    colorOut = vec4(difCol,alpha);
    normalOut = vec4(calculateNormalMap(), 1.0);


	// This is for picking objects that are not instance drawn but are still references
	uint refID = referenceIndex;
	if (singleRefIndex != -1)
		refID = singleRefIndex;

    pickingOut = uvec3(objectIndex, refID, 0);
};